//
//  CNGameClient.m
//  chuiniu
//
//  Created by zheng ji on 14-9-21.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "CNGameClient.h"
#import "constants.h"
#import "CommandDef.h"
#import "CNAppDelegate.h"
#import "CommonConfigUtil.h"
#import "CNGameUtil.h"

@interface CNGameClient ()
{
    NSUserDefaults* _userDefaults;
    GCDAsyncSocket* _asyncSocket;
    CNAppDelegate* appDelegate;
    BOOL _playerLogined;
}
@end
@implementation CNGameClient

- (id) init
{
    if(self = [super init])
    {
        _userDefaults=[NSUserDefaults standardUserDefaults];
        
        appDelegate=(CNAppDelegate*)[UIApplication sharedApplication].delegate;
    }
    return self;
}
-(void)connectToServer{
    NSString *host = @"192.168.1.101";
     host = @"106.3.228.227";
    uint16_t port = 9999;
    
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    
    _asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
    
    NSError *error = nil;
    
    [_asyncSocket connectToHost:host onPort:port error:&error];
    
    
}
//发送检查设备是否注册消息
-(void)sendCheckDeviceRegisgerCommand{
    NSString *deviceID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSString* json=[NSString stringWithFormat:@"{cmd:'%@',did:'%@'}",CommandCheckDeviceRegister,deviceID];
    [self sendMessage:json];
}
/**
 发送获取在线玩家列表的命令
 
 */
-(void)sendOnlinePlayerCommand:(NSString*) playerId startRecordNo:(int)startRecordNo endRecordNo:(int)endRecordNo{
    
    
    NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@,f:%d,t:%d}",CommandOnlinePlayer,playerId,startRecordNo,endRecordNo];
    [self sendMessage:json];
}
/**
 发送猜测超时消息
 playerID: 超时玩家
 vsPlayerID: 对家
 chipCoins: 金币
 */
-(void)sendGuessTimeOver:(NSString*)playerID vsPlayerID:(NSString*)vsPlayerID  chipCoins:(int)chipCoins{
    NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@,vsid:%@,cn:%d}",CommandGuessTimeOver,playerID,vsPlayerID,chipCoins];
    [self sendMessage:json];
}

/**
 发送猜测的数据
 count:数量
 number:骰子点数
 */
-(void)sendGuessNumber:(CNPlayer*)player count:(int)count number:(int)number{
    
    NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@,d:'%d,%d'}",CommandGuessData,player.playerID,count,number];
    [self sendMessage:json];
}
/**
  开看结果
 */
-(void)sendOpenMatch:(NSString*)playerId win:(int)win vsPlayerId:(NSString*)vsPlayerId{
     NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@,vsid:%@,win:%d}",CommandOpenMatch,playerId,vsPlayerId,win];
    [self sendMessage:json];
}
/*发送摇定好的骰子点数到服务器，
 
 diceNums:多个点数之间用逗号隔开
 */
-(void)sendDiceNumbers:(CNPlayer*)player diceNumbers:(NSString*) diceNums{
    
    NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@,d:'%@'}",CommandDiceNumber,player.playerID,diceNums];
    [self sendMessage:json];
}

/**
 金币处理
 */
-(void)sendGoldCoinCommand:(CNPlayer*)player coins:(int)coins tradeType:(GoldCoinTradeType) tradeType  money:(double)money{
    NSString* deviceType=@"ipad";
    if(  IsIPhone){
        deviceType=@"iphone";
    }
    NSString *deviceID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSString* guid=[CNGameUtil CreateGUID];
    
    NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@,n:'%@',coins:%d,tt:%d,dt:'%@',did:'%@',guid:'%@',money:%f}",CommandGoldTrade,player.playerID,player.playerName,coins,(int)tradeType,deviceType,deviceID,guid,money];
    
    if(self.isConnected){//有网络连接，则发送到服务器
      
      [self sendMessage:json];
    }else{
        //无网络连接保存到本地
       NSString* localFile=[NSString stringWithFormat:@"%@.json",guid];
        
        [CNGameUtil writeGoldContentToFile:json goldFileName:localFile];
    }
    
}
/**
 保存玩家名称到服务器
 */
-(void)savePlayerNameToServer:(NSString*)name playerId:(NSString*)playerId{
    NSString* json=[NSString stringWithFormat:@"{cmd:'spn',id:%@,n:'%@'}",playerId,name];
    
    [self sendMessage:json];

}
/**
  注册玩家
 */
-(void)registerPlayer:(NSString*)playerName{
    NSString *deviceID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSString* deviceType=@"iphone";
    if(!IsIPhone) deviceType=@"ipad";
    
    NSString* json=[NSString stringWithFormat:@"{cmd:'rg',did:'%@',dt:'%@',n:'%@'}",deviceID,deviceType,playerName];
    
    [self sendMessage:json];
    
    
}

-(void)parseResponseMessage:(NSString*)message{
    if(message==nil || [message isEqualToString:@""]) return;
      NSArray* array=[message componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet ]];
    if(array !=nil){
        for (NSString* msg in array) {
            [self parseMessage:msg];
        }
    }
}
/**
 解析服务器传递来的消息
 */
-(void)parseMessage:(NSString*)message{
    if(message==nil || [message isEqualToString:@""]) return;
    
  
    NSLog(@"receiveMessage:%@",message);
    //  NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
    
    
    NSError *error=nil;
 
      //  NSDictionary* di=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];;
    
    if(!error){
        
        NSString* cmd=[dictionary objectForKey:@"cmd"];
        if([cmd isEqualToString:CommandRegisterPlayer]){
            //注册用户返回数据
            [self receivePlayerInfo:dictionary];
        }else if([cmd isEqualToString:CommandRequestPK]){
            //有玩家请求对战
            [self receivePKCommand:dictionary];
        }else if([cmd isEqualToString:CommandSavePlayerName]){
            //保存玩家名称
            [self receiveSavePlayerNameCommand:dictionary];
        }else if([cmd isEqualToString:CommandStartShakeDice]){
            //可以开始摇动骰子了
            [self receiveStartShakeDiceCommand:dictionary];
        }else if([cmd isEqualToString:CommandDiceNumber]){
            //发送摇定好的所有点数给服务器后，返回的消息
            [self receiveDiceNumberResponse:dictionary];
            
        }else if([cmd isEqualToString:CommandVSPlayerDiceNumbers]){
            //接收到对家摇定骰子点数
            [self receiveVSPlayerDiceNumbers:dictionary];
        }else if([cmd isEqualToString:CommandStartGuess]){
            //接收到可以开始猜测的消息
            [self receiveStartGuess:dictionary];
        }else if([cmd isEqualToString:CommandSelectPlayer]){
            //选择对战命令返回消息
            [self receiveSelectCommand:dictionary];
        }else if([cmd isEqualToString:CommandOnlinePlayer]){
            //返回在线玩家列表
            [self receiveOnlinePlayer:dictionary];
        }else if([cmd isEqualToString:CommandSendGuessDataVS]){
            //对家猜测数据
            [self receiveVSPlayerGuessData:dictionary];
        }else if([cmd isEqualToString:CommandOpenMatch]){
            //开看结果
            [self receiveOpenMatch:dictionary];
        }else if([cmd isEqualToString:CommandPlayerClosed]){
            //对家下线
            [self receivePlayerClosed:dictionary];
        }else if([cmd isEqualToString:CommandGoldTrade]){
            //金币交易
            [self receiveGoldTrade:dictionary];
        }else if([cmd isEqualToString:CommandGoldCoinProduct]){
            //从服务器接收金币产品列表
            [self receiveGoldCoinProduct:dictionary];
        }else if([cmd isEqualToString:CommandCheckDeviceRegister]){
            //从服务器接收到当前设备注册的玩家
            [self receiveRegisterDevice:dictionary];
        }else if([cmd isEqualToString:CommandLogin]){
            
            [self receiveLogin:dictionary];
        }



        
    }
}
-(void)receiveLogin:(NSDictionary*)dict{
    if(dict==nil) return ;
    NSString* code=[dict objectForKey:@"c"];
    if([code intValue]==ResponseCodeSuccess){
        _playerLogined=YES;
    }else{
        _playerLogined=NO;
    }
}
//从服务器接收到当前设备注册的玩家
-(void)receiveRegisterDevice:(NSDictionary*)dict{
    if(dict==nil) return ;
    
    CNPlayer* player=[[CNPlayer alloc]init];
    player.playerID=[dict objectForKey:@"id"];
    player.levelName=[dict objectForKey:@"levelname"];
    player.playerName=[dict objectForKey:@"playername"];
    player.coins=[dict objectForKey:@"coins"];
    
    [CNGameUtil saveCurrentPlayerToUserDefaults:player];
    
}
/**
 从服务器接收金币产品列表
 */
-(void)receiveGoldCoinProduct:(NSDictionary*)dict{
    if(dict==nil) return ;
    
    appDelegate.goldCoinProducts=[dict objectForKey:@"d"];
    /*
    NSArray* array=[dict objectForKey:@"d"];
    
    appDelegate.goldCoinProduct=[[NSMutableDictionary alloc]init];
    if(array!=nil){
        
        for (NSDictionary* product in array) {
            
           NSString* key=[product objectForKey:@"productid"];
            NSString* value=[product objectForKey:@"goldcoins"];
            
         
            [appDelegate.goldCoinProduct setValue:[product objectForKey:@"goldcoins"] forKey:[product objectForKey:@"productid"]];
        }
        
        
    }
    */
    
}
/**
  接收到金币交易结果
 */
-(void)receiveGoldTrade:(NSDictionary*)dict{
    if(dict==nil) return ;
    
    
    NSString* goldFile=[NSString stringWithFormat:@"%@.json",[dict objectForKey:@"guid"]];
  
    [CNGameUtil removeLocalGoldFile:goldFile];
    
}
/**
 对家已经下线
 */
-(void)receivePlayerClosed:(NSDictionary*)dict{
    if(dict==nil) return ;
    
    if(self.gameMainViewController !=nil
       && [self.gameMainViewController respondsToSelector:@selector(vsPlayerOffline)]){
    
        [self.gameMainViewController vsPlayerOffline];//对家已经下线
    }
    
}
/**
  开看结果
 */
-(void)receiveOpenMatch:(NSDictionary*)dict{
    if(dict==nil) return ;
    
    NSString* win=[dict objectForKey:@"win"];
    NSString* coins=[dict objectForKey:@"coins"];
    
  /*  if(self.gameMainViewController !=nil
       && [self.gameMainViewController respondsToSelector:@selector(setMatchResult:)]){
     [self.gameMainViewController setMatchResult:win.intValue coins:coins.intValue];
    }*/
    
    [self.gameMainViewController setMatchResult:win.intValue coins:coins.intValue];
    
}
//对家猜测数据
-(void)receiveVSPlayerGuessData:(NSDictionary*)dict{
    if(dict==nil) return ;
   NSString* data =[dict objectForKey:@"d"];
    NSArray *array=[data componentsSeparatedByString:@","];
    NSString* count=[array objectAtIndex:0];
    NSString* number=[array objectAtIndex:1];
    /*if(self.gameMainViewController !=nil
       && [self.gameMainViewController respondsToSelector:@selector(setVSPlayerGuessData:)]){
        
    [self.gameMainViewController setVSPlayerGuessData:[dict objectForKey:@"vsid"] count:count.intValue number:number.intValue];
    }*/
    
    
    [self.gameMainViewController setVSPlayerGuessData:[dict objectForKey:@"vsid"] count:count.intValue number:number.intValue];
}
/**从服务器返回的 cmd:su*/
-(void)receiveOnlinePlayer:(NSDictionary*)dict{
    if(dict==nil) return ;
    NSMutableArray* playerList=[[NSMutableArray alloc]init];
    NSArray* arrayPlayer=[dict objectForKey:@"d"];
    
    if(arrayPlayer!=nil){
        for (NSDictionary* dictPlayer in arrayPlayer) {
            CNPlayer* p=[[CNPlayer alloc]init];
            p.playerID=[dictPlayer objectForKey:@"id"];
            p.playerName=[dictPlayer objectForKey:@"name"];
            p.levelName=[dictPlayer objectForKey:@"levelName"];
            p.coins=[dictPlayer objectForKey:@"coins"];
            NSNumber* num=[dictPlayer objectForKey:@"playing"];
            p.playing=num.intValue==1?YES:NO;
            
            [playerList addObject:p];
        }
    }
    
    if(playerList.count>0){
        if(self.gameMainViewController !=nil
           && [self.gameMainViewController respondsToSelector:@selector(addOnlinePlayerList:)]){
            
        [self.gameMainViewController addOnlinePlayerList:playerList];
        }
    }
    
}
/**从服务器返回的 cmd:su*/
-(void)receiveSelectCommand:(NSDictionary*)dict{
     if(dict==nil) return ;
    NSString* code=[dict objectForKey:@"c"];
    if([code intValue]==ResponseCodePlayerOffline ){
        //对家已经下线
        [CommonConfigUtil showToast:kToastPositionCenter duration:kToastDurationShort withTitle:@"对家已经不在线,请邀请其他玩家"];
    }else if([code intValue]==ResponseCodePlayerAlreadyPK ){
        //对家正在对战中
         [CommonConfigUtil showToast:kToastPositionCenter duration:kToastDurationShort withTitle:@"对家正在对战中,请邀请其他玩家"];
    }else if([code intValue]==ResponseCodePlayerRejectPK ){
        //对家拒绝对战
        
           [CommonConfigUtil showToast:kToastPositionCenter duration:kToastDurationShort withTitle:@"对家拒绝对战邀请,请邀请其他玩家"];
    }else if([code intValue]== ResponseCodeSuccess){
        //接受对战
        [self setVSPlayer:dict ];
    }
    
    
}
/**
  接受对战请求
 */
-(void)setVSPlayer:(NSDictionary*)dict{
    if(dict==nil) return ;
    CNPlayer* vsPlayer=[[CNPlayer alloc]init];
    vsPlayer.playerID=[dict objectForKey:@"vsid"];
    vsPlayer.levelName=[dict objectForKey:@"ln"];
    vsPlayer.playerName=[dict objectForKey:@"n"];
    
    if(self.gameMainViewController !=nil
       && [self.gameMainViewController respondsToSelector:@selector(setVSPlayer:)]){
        
    [self.gameMainViewController setVSPlayer:vsPlayer];
    }
}
//接收到可以开始猜测的消息
-(void)receiveStartGuess:(NSDictionary*)dict{
     if(dict==nil) return ;
    NSString* code=[dict objectForKey:@"c"];
    
    if([code intValue]==ResponseCodeWaitVSPlayerGuess ){
        //等待对方先猜测
        if(self.gameMainViewController !=nil
           && [self.gameMainViewController respondsToSelector:@selector(waitVSPlayerGuess)]){
        [self.gameMainViewController waitVSPlayerGuess];
        }
    }else if([code intValue]==ResponseCodeSuccess ){
        //自己先猜测
      [self.gameMainViewController startGuessNumber];
    }
}
//接收到对家摇定的所有骰子点数
-(void)receiveVSPlayerDiceNumbers:(NSDictionary*)dict{
    if(dict==nil) return ;
    
    NSString* numbers=[dict objectForKey:@"d"];
    NSArray* array=  [numbers  componentsSeparatedByString:@","];
   // NSMutableArray* mutArray=[NSMutableArray arrayWithArray:array];
    
    if(self.gameMainViewController !=nil
       && [self.gameMainViewController respondsToSelector:@selector(setVSPlayerAllDiceNumbers:)]){
        
    [self.gameMainViewController setVSPlayerAllDiceNumbers:[NSMutableArray arrayWithArray:array]];
    }
}

//发送摇定好的所有点数给服务器后，返回的消息
-(void)receiveDiceNumberResponse:(NSDictionary*) dict{
    
    if(dict==nil) return ;
    
    NSString* code=[dict objectForKey:@"c"];
    
    if(code !=nil && [code intValue] ==ResponseCodeWaitVSPlayerShaked){
        //等待对方摇动骰子
        
        if(self.gameMainViewController !=nil
           && [self.gameMainViewController respondsToSelector:@selector(waitVSPlayerShake)]){
            
        [self.gameMainViewController waitVSPlayerShake];
        }
    }
}
/*
 接收到开始摇动骰子
 */
-(void)receiveStartShakeDiceCommand:(NSDictionary*)dict{
    
    if(self.gameMainViewController !=nil
       && [self.gameMainViewController respondsToSelector:@selector(startShakeDiceInMutilPlayer)]){
        
    [self.gameMainViewController startShakeDiceInMutilPlayer];
    }
}
/*
 接收到对战请求
 */
-(void)receiveSavePlayerNameCommand:(NSDictionary*)dict{
    if(dict==nil) return ;
    NSInteger code=[dict objectForKey:@"c"];
    if(code ==ResponseCodeSuccess){
        NSLog(@"");
    }
}
/*
   接收到对战请求
 */
-(void)receivePKCommand:(NSDictionary*)dict{
    if(dict==nil) return ;
    
    if(appDelegate.vsPlayer ==nil && (appDelegate.scence == ScenceMainView ||
                                      appDelegate.scence==ScenceGameSet
                                      || appDelegate.scence==ScencePlayerLevel
                                      || (appDelegate.scence==ScencePlayView
                                           && appDelegate.gamePlayModel==GameModelSinglePlayer))){//接收对战请求
      CNPlayer* vsPlayer=[[CNPlayer alloc]init];
      vsPlayer.playerID=[dict objectForKey:@"id"];
      vsPlayer.playerName=[dict objectForKey:@"n"];
      vsPlayer.levelName=[dict objectForKey:@"ln"];
                              
    if(self.gameMainViewController !=nil
         && [self.gameMainViewController respondsToSelector:@selector(requestPK:)]){
                [self.gameMainViewController requestPK:vsPlayer];
        }
                                          
    }else{//拒绝对战
        
        
        if(self.gameMainViewController !=nil
           && [self.gameMainViewController respondsToSelector:@selector(sendRejectVSCommand:)]){
            
        CNPlayer* player= [CNGameUtil getCurrentPlayerFromUserDefaults];
        [self sendRejectVSCommand:player vsPlayerID:[dict objectForKey:@"id"]];
        }
    }
}
/*接收到服务器返回玩家的基本数据*/
-(void)receivePlayerInfo:(NSDictionary*)dict{
    if(dict==nil) return ;
    CNPlayer* player=[[CNPlayer alloc]init];
    player.playerID=[dict objectForKey:@"id"];
    player.playerName=[dict objectForKey:@"n"];
    player.levelName=[dict objectForKey:@"ln"];
    player.coins=[dict objectForKey:@"cn"];
    appDelegate.player=player;
    [CNGameUtil saveCurrentPlayerToUserDefaults:player];
    
    NSString* regName=[dict objectForKey:@"regname"];//当前注册时填写的昵称
    
    if(regName!=nil && [regName isEqualToString:player.playerName]){
        //当前注册的昵称，与当前设备以前注册昵称不一样。
        UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:@"" message:[NSString stringWithFormat:@"是否使用回您以前注册的[%@]?",player.playerName ] delegate:self cancelButtonTitle:@"是" otherButtonTitles:@"否", nil];
        [alertView show];
        alertView=nil;
    }else{
        [CommonConfigUtil showToast:kToastPositionCenter duration:kToastDuration2Second withTitle:@"注册成功,可以开始游戏了。"];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        //修改玩家昵称
        NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@,playername:'%@'}",CommandUpdatePlayerName,appDelegate.player.playerID,appDelegate.player.playerName];
        
        [self sendMessage:json];
    }
}

-(void)sendMessage:(NSString*)message{
    if(!_asyncSocket.isConnected) return ;
    
    if(message==nil || [message isEqualToString:@""]) return ;
    
    message=[NSString stringWithFormat:@"%@\r\n",message];
    NSLog(@"sendMessage:%@",message);
  //  NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
    
    [_asyncSocket writeData:data withTimeout:-1 tag:1];
}

/**
 发送准备好开始游戏命令
 */
-(void)sendReadyPlayCommand:(CNPlayer*)player vsPlayer:(CNPlayer*)vsPlayer{
    NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@,vsid:%@}",CommandReadyPlay,player.playerID,vsPlayer.playerID];

    [self sendMessage:json];
}
/**
 发送退出游戏消息
 */
-(void)sendQuitGameCommand{
    if(appDelegate.player !=nil){
       NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@}",CommandQuitLogin,appDelegate.player.playerID];
        
        [self sendMessage:json];
        
        _playerLogined=NO;
    }
}
/**
 选择玩家对战
 
 **/
-(void)sendSelectPlayerCommand:(NSString*)playerID vsPlayerID:(NSString*)vsPlayerID{
    NSString* json=[NSString stringWithFormat:@"{cmd:'%@',id:%@,vsid:%@}",CommandSelectPlayer,playerID,vsPlayerID];
    [self sendMessage:json];
}


-(void)sendRejectVSCommand:(CNPlayer*)vsPlayer{
    
    [self sendRejectVSCommand:[CNGameUtil getCurrentPlayerFromUserDefaults] vsPlayerID:vsPlayer];
}
/**
 发送拒绝对战命令
 */
-(void)sendRejectVSCommand:(CNPlayer*)player vsPlayerID:(CNPlayer*)vsPlayer{
    [self sendMessage:[NSString stringWithFormat:@"{cmd:'%@',id:%@,vsid:%@,c:%d}",CommandRequestPK,player.playerID,vsPlayer.playerID,ResponseCodeFailure]];
}
/**
 发送接收对战命令
 */
-(void)sendAcceptVSCommand:(CNPlayer*)player vsPlayerID:(CNPlayer*)vsPlayer{
    [self sendMessage:[NSString stringWithFormat:@"{cmd:'%@',id:%@,vsid:%@,c:%d}",CommandRequestPK,player.playerID,vsPlayer.playerID,ResponseCodeSuccess]];
}
-(void)sendLoginCommand:(CNPlayer*) player{
    if(_playerLogined) return ;
     NSString *deviceID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [self sendMessage:[NSString stringWithFormat:@"{cmd:'%@',id:%@,did:'%@'}",CommandLogin,player.playerID,deviceID]];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Socket Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    
    self.isConnected=true;
    
    //[sock readDataWithTimeout:-1 tag:0];
    
    [sock readDataWithTimeout:-1 tag:0];
   
    CNPlayer* player=[CNGameUtil getCurrentPlayerFromUserDefaults];
    if(player!=nil){
        [self sendLoginCommand:player];
    }
    //上传未处理的金币记录
    [NSThread detachNewThreadSelector:@selector(downloadGoldCoinProdcts) toTarget:self withObject:nil];
    //上传未处理的金币记录
    [NSThread detachNewThreadSelector:@selector(uploadGoldTradeFile) toTarget:self withObject:nil];
    
}
/**
 从服务器下载金币产品列表
 */
-(void)downloadGoldCoinProdcts{
    NSString* json=[NSString stringWithFormat:@"{cmd:'%@'}",CommandGoldCoinProduct];
    [self sendMessage:json];//获取金币购买列表
    
    [self sendCheckDeviceRegisgerCommand];//检查当前设备是否已经注册玩家
}
 //上传未处理的金币记录
-(void)uploadGoldTradeFile{
     NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError* error;
    
   NSArray* array=   [fileManager contentsOfDirectoryAtPath:[CNGameUtil getLocalGoldPath] error:&error ];
    if(array !=nil){
        
        
        for (NSString* file in array) {
            
            NSString* content=[CNGameUtil readGoldContentFromFile:file];
            if(content !=nil){
                [self sendMessage:content];
            }
           // [fileManager removeItemAtPath:file error:nil];
        }
    }
    
    fileManager=nil;
    
}

- (void)socketDidSecure:(GCDAsyncSocket *)sock
{
    
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    //NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    // NSString* message = [[NSString alloc] initWithData:data encoding:gbkEncoding];
    NSString* message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [sock readDataWithTimeout:-1 tag:0];
    [self parseResponseMessage:message];
    
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    self.isConnected=false;
    _playerLogined=NO;

}


@end
